import requests
from pprint import pprint
import csv

f = open ('data.csv',mode='w',encoding='utf-8',newline='')
csv_writer = csv.DictWriter(f,fieldnames=[
    '股票代码' ,
    '股票名称' ,
    '当前价' ,
    '涨跌额' ,
    '涨跌幅' ,
    '年初至今' ,
    '成交量',
    '成交额',
    '换手率',
    '市盈率(TTM)',
    '股息率' ,
    '市值' ,
    '详情页' ,
])
csv_writer.writeheader()#写入表头
 

url = 'https://stock.xueqiu.com/v5/stock/screener/quote/list.json?page=2&size=30&order=desc&orderby=percent&order_by=percent&market=CN&type=sh_sz'

headers = {
    'Cookie':'cookiesu=831699434665676; device_id=02607d2f37cdd8352c3018c2d21c4dee; s=b1134qnxjj; xq_a_token=cf755d099237875c767cae1769959cee5a1fb37c; xqat=cf755d099237875c767cae1769959cee5a1fb37c; xq_r_token=e073320f4256c0234a620b59c446e458455626d9; xq_id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1aWQiOi0xLCJpc3MiOiJ1YyIsImV4cCI6MTcwMTk5NTg4MCwiY3RtIjoxNjk5NDM1Nzc0NTg1LCJjaWQiOiJkOWQwbjRBWnVwIn0.U7nuUStSkQo7vMgKATnN9IQg1r2cmFKmqOpyWTQ0rm3iQHnGp0JooHBElIzDLRVjpqbyI_dfi1gWe1RvJ-qLOw3_lATQ_LCjEwt1YMkkN8NtQtpZS9GSNoWvoC8__RYBQYEWLSY2alNSwW4snt5F9Q3csErCHniOJNe5dWlJYHTqLZKXz1XEzrYx10calq-t6odDhoIq9Q2mzUn3-5thDF66Rum2mmtW6C44OqAe6SRKW6pN3GhcrYg1wZJ-31dGEjC8ZxvKWSI2QF1V50OptjHTRK_gx-8YX4sVOpOmJaBeIjI_Vj3GpBB1caR_rQzdrHSt4raW0PaCNpVdD8t1hA; u=831699434665676; Hm_lvt_1db88642e346389874251b5a1eded6e3=1699434666,1699435793; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1699435798',

    'User-Agent' : 'Mozilla/5.e (Windons NI 18.8; Winb4;x54)AppleWebkit/537.36(KHIML,like Gecko) Chrome/113.0.0.8 Safari/537.36', 'x-requested-with': 'XMLiIttpHequest',
    } 

response = requests.get(url=url ,headers=headers)
#print(response)
#print(response.json()['data']['list'])


for index in response.json()['data']['list']:
    #print(index)
    #pprint(index)
    dit = {
        '股票代码' : index['symbol'],
        '股票名称' : index['name'],
        '当前价' : index['current'],
        '涨跌额' : index['chg'],
        '涨跌幅' : index['amplitude'],
        '年初至今' : index['current_year_percent'],
        '成交量' : index['volume'],
        '成交额' : index['amount'],
        '换手率' : index['turnover_rate'],
        '市盈率(TTM)' : index['turnover_rate'],
        '股息率' : index['dividend_yield'],
        '市值' : index['float_market_capital'],
        '详情页' : f'https://xueqiu.com/S/{index["symbol"]}', 
    }
    csv_writer.writerow(dit)
 